/* Main entry point for the khipu API.

   This file is part of khipu.

   khipu is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */

#include <cstdio>
#include <cstdlib>
#include "khipu.hpp"

using namespace khipu;

int main (int argc, char **argv)
{
  if (!khipu_init ())
    {
      fputs ("failed to initialize khipu runtime\n", stderr);
      return (0);
    }

  interpreter *interp = main_interp;
  valref last_expr (interp, intern (interp, "_"));
  reader rd (interp, in_stream);
  stream *outs = as_stream (out_stream), *errs = as_stream (err_stream);
  io_info info;

  for (info.flags = 0 ; ; )
    {
      outs->write (interp, "khipu> ", 7);
      outs->flush (interp);

      try
        {
          object expr = rd.read_sexpr ();
          if (expr == EOS)
            break;

          object evo = eval (interp, expr);
          xwrite (interp, outs, evo, info);
          symval(*last_expr) = evo;
          outs->putb (interp, '\n');
        }
      catch (exception& exc)
        {
          if (interp->throw_frame != 0)
            print_backtrace (interp, interp->throw_frame, errs, info);

          write_exc (interp, errs, exc.value, info);
          errs->putb (interp, '\n');
          errs->flush (interp);

          interp->reset_exc ();
        }
    }

  outs->putb (interp, '\n');
  outs->flush (interp);
  return (0);
}

